import { login, logout } from '@/api/admin/login'
import { info as userInfo } from '@/api/admin/user-center'
import {
  setAdminToken,
  getAdminToken,
  delAdminToken,
  setNickname,
  delNickname,
  setAvatar,
  delAvatar
} from '@/utils/auth'
import router, {
  resetRouter
} from '@/router'
import { getRule } from '@/utils/util'

const state = {
  adminToken: getAdminToken(),
  username: '',
  nickname: '',
  avatar: '',
  roles: []
}

const mutations = {
  SET_ADMINTOKEN: (state, adminToken) => {
    state.adminToken = adminToken
  },
  SET_NICKNAME: (state, nickname) => {
    state.nickname = nickname
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // 登录
  login({ commit }, userInfo) {
    const {
      account,
      password
    } = userInfo
    return new Promise((resolve, reject) => {
      login({
        account: account,
        password: password
      }).then(response => {
        const { data } = response
        commit('SET_ADMINTOKEN', data.token)
        setAdminToken(data.token)
        commit('SET_NAME', data.accountInfo.nickName)
        localStorage.setItem('userInfo', JSON.stringify(data.accountInfo))
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取用户信息
  userInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      const data = JSON.parse(sessionStorage.getItem('userInfo'))
      data.roles = getRule(data.menuList, 0)
      if (data) {
        const { nickName, avatar } = data
        commit('SET_NAME', nickName)
        commit('SET_AVATAR', avatar)
        commit('SET_ROLES', data.roles)
        resolve(data)
      } else {
        reject()
      }
    })
  },

  // 退出
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout().then(() => {
        commit('SET_ADMINTOKEN', '')
        commit('SET_ROLES', [])
        delAdminToken()
        delNickname()
        delAvatar()
        resetRouter()

        // 重置访问的视图和缓存的视图
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 重置token
  resetAdminToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_ADMINTOKEN', '')
      commit('SET_ROLES', [])
      delAdminToken()
      resolve()
    })
  },

  // 动态修改权限
  async changeRoles({ commit, dispatch }, role) {
    const adminToken = role + '-adminToken'

    commit('SET_ADMINTOKEN', adminToken)
    setAdminToken(adminToken)

    const { roles } = await dispatch('userInfo')

    resetRouter()

    // 根据权限生成可访问路由
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })

    // 动态添加可访问路由
    router.addRoutes(accessRoutes)

    // 重置访问的视图和缓存的视图
    dispatch('tagsView/delAllViews', null, { root: true })
  },

  getRole({ commit }) {
    const userInfo = JSON.parse(localStorage.getItem('userInfo'))
    const role = getRule(userInfo?.menuList, 0)
    const roles = []
    role.forEach((item) => {
      roles.push('admin/admin.' + item + '/getList')
      roles.push('admin/admin.' + item + '/add')
      roles.push('admin/admin.' + item + '/info')
      roles.push('admin/admin.' + item + '/edit')
    })
    commit('SET_ROLES', roles)

    return roles
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
